<template>
    <div v-if="!taskId" class="w-full h-full flex justify-center">
        <div class="w-[50%]">
            <ElCard class="h-full" body-class="h-full">
                <template #header>
                    <p class="text-center font-bold text-2xl">合同审查</p>
                </template>
                <div class="h-full flex flex-col gap-4 justify-center items-center">
                    <ElSelect placeholder="请选择合同类型" v-model="type" :options="options" :props="{label:'name',value:'english'}"></ElSelect>
                    <ElUpload ref="upload" class="w-full" :limit="1" drag :multiple="false" :auto-upload="false"
                        :on-exceed="fileChange" :http-request="request">
                        <ElIcon class="el-icon--upload">
                            <UploadFilled />
                        </ElIcon>
                        <div class="el-upload__text">
                            拖入文件或 <em>点击上传</em>
                        </div>
                    </ElUpload>
                    <ElButton class="w-full" type="primary" @click="submitUpload">确定</ElButton>
                </div>
            </ElCard>
        </div>
    </div>
    <div v-else class="h-full w-full">
        <iframe class="w-full h-full"
            :src="`https://textmind-sdk.bce.baidu.com/textmind/sdk/textreview/${taskId}?access_token=${token}`"
            frameborder="0"></iframe>
        <ElButton class="absolute w-40 left-5 bottom-5" type="primary" @click="close">关闭</ElButton>
    </div>
</template>

<script setup lang='ts' name=''>
import { ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue';
import { ElCard, ElUpload, genFileId, ElIcon, ElButton, ElMessage, ElSelect } from 'element-plus';
import { contractType, getToken, uploadFile } from '@/api/contract';
const token = ref('')
const taskId = ref('')
const type = ref('')
const upload = ref()
const options = ref([])

/** 添加文件 */
function fileChange(files: any) {
    upload.value!.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
/** 上传文件 */
function submitUpload() {
    upload.value.submit()
}
/** 上传文件请求 */
async function request(options: any) {
    if(!type.value){
        ElMessage.error('请选择合同类型')
        return
    }
    const res: any = await uploadFile(options.file,type.value)
    if (res.code === 200) {
        ElMessage.success('上传成功')
        taskId.value = res.data
    }
}
/** 关闭 */
function close() {
    taskId.value = ''
}
/** 获取合约token */
const tokenData = localStorage.getItem('contractToken')
if (!tokenData || tokenData === "undefined") {
    getToken().then(res => {
        // 存储token和过期时间（5天后）
        const expireTime = Date.now() + (5 * 24 * 60 * 60 * 1000)
        const tokenInfo = {
            token: res.data,
            expireTime: expireTime
        }
        localStorage.setItem('contractToken', JSON.stringify(tokenInfo))
        token.value = res.data
    })
} else {
    try {
        const parsedToken = JSON.parse(tokenData)
        // 检查token是否过期
        if (parsedToken.expireTime && Date.now() > parsedToken.expireTime) {
            // token过期，重新获取
            getToken().then(res => {
                const expireTime = Date.now() + (5 * 24 * 60 * 60 * 1000)
                const tokenInfo = {
                    token: res.data,
                    expireTime: expireTime
                }
                localStorage.setItem('contractToken', JSON.stringify(tokenInfo))
                token.value = res.data
            })
        } else {
            token.value = parsedToken.token
        }
    } catch (e) {
        // 解析失败，重新获取token
        getToken().then(res => {
            const expireTime = Date.now() + (5 * 24 * 60 * 60 * 1000)
            const tokenInfo = {
                token: res.data,
                expireTime: expireTime
            }
            localStorage.setItem('contractToken', JSON.stringify(tokenInfo))
            token.value = res.data
        })
    }
}

/** 获取合同类型 */
contractType().then(res => {
    options.value = res.data
})
</script>
<style scoped></style>